package com.hmy.finance.service.statement.statementHandlerFactory;

import com.hmy.ccp.error.exception.HMYRuntimeException;
import com.hmy.finance.api.bo.core.request.enums.StatementTypeEnum;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.collections4.MapUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @desc：账单生成执行器context
 * @author：wenjian
 * @date：2024-04-03
 */
@Component
public class StatementHandlerFactory implements ApplicationListener<ContextRefreshedEvent> {
    private static Map<StatementTypeEnum, DefaultStatementHandler> HANDLER_MAP = new ConcurrentHashMap<>(16);

    /**
     * 根据类型获取对应执行器
     *
     * @param statementTypeEnum
     * @return
     */
    public static DefaultStatementHandler getHandlerByType(StatementTypeEnum statementTypeEnum) {
        DefaultStatementHandler statementTypeHandle = HANDLER_MAP.get(statementTypeEnum);
        if (Objects.isNull(statementTypeHandle)) {
            throw new HMYRuntimeException("账单生成执行器不存在");
        }
        return statementTypeHandle;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Map<String, DefaultStatementHandler> executors = contextRefreshedEvent.getApplicationContext().getBeansOfType(DefaultStatementHandler.class);
        if (MapUtils.isNotEmpty(executors)) {
            HANDLER_MAP = executors.values().stream().collect(Collectors.toMap(DefaultStatementHandler::getStatementEnumType, Function.identity()));
        }
    }
}
